<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Main extends CI_Controller
{

    /**
     * 构造函数
     *
     * @access  public
     * @return  void
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('islogin');
        islogin();

        //ftp全局用户
        $this->s_user = 'ftp_super';

        //ftp混淆字符串
        $this->ftp_secret = 'abc123';

        //mysql混淆字符串
        $this->mysql_secret = 'abc123';

        //临时域名
        $this->domain_tmp = 't.xxx.com';

        //临时域名开始端口
        $this->domain_ports = '10300';

        //每页显示条数
        $this->num = 10;
    }

    /**
     * 站点列表
     *
     * @access  public
     * @return  void
     */
    public function index()
    {
        /* 载入自定义辅助函数 */
        $this->load->helper('pager'); //自定义的翻页函数
        $this->load->helper('mydb'); //自定义的数据库函数

        $data     = array();
        $keys     = $this->input->get('keys');
        $is_visit = $this->input->get('is_visit');
        $is_ftp   = $this->input->get('is_ftp');
        $is_mysql = $this->input->get('is_mysql');
        $sql_c    = "SELECT COUNT(s_id) FROM " . $this->db->dbprefix('site');
        $sql      = "SELECT * FROM " . $this->db->dbprefix('site');
        $where    = ' WHERE 1=1';
        $where .= empty($keys) ? '' : " AND (uname LIKE '%$keys%' OR domain LIKE '%$keys%' OR dir LIKE '%$keys%')";
        $where .= $is_visit == '' ? '' : " AND is_visit='$is_visit'";
        $where .= $is_ftp == '' ? '' : " AND is_ftp='$is_ftp'";
        $where .= $is_mysql == '' ? '' : " AND is_mysql='$is_mysql'";

        //得到总记录数，无需order by
        $sql_c .= $where;
        $total = get_one($sql_c);

        if ($total > 0) {
            //order by
            $sql .= $where . ' ORDER BY addtime DESC';

            //设置每页显示
            $num   = $this->num;
            $pages = ceil($total / $num);
            $page  = isset($_GET['page']) ? intval($_GET['page']) : 0;
            $page  = empty($page) ? 1 : ($page > $pages ? $pages : $page);

            //得到数据
            $start = ($page - 1) * $num < 0 ? 0 : ($page - 1) * $num;
            $limit = " LIMIT $start, $num";
            $sql .= $limit;
            $url = 'main/?1=1';
            $url .= empty($keys) ? '' : '&keys=' . $keys;
            $url .= empty($is_visit) ? '' : '&is_visit=' . $is_visit;
            $url .= empty($is_ftp) ? '' : '&is_ftp=' . $is_ftp;
            $url .= empty($is_mysql) ? '' : '&is_mysql=' . $is_mysql;
            $url .= "&";

            $data['keys']     = $keys;
            $data['is_visit'] = $is_visit;
            $data['is_ftp']   = $is_ftp;
            $data['is_mysql'] = $is_mysql;
            $data['page']     = $page;
            $data['pager']    = pager($url, $total, $page, $num);
            $data['list']     = get_all($sql);
        }
        $this->load->view('main_list', $data);
    }


    /**
     * 增加站点
     *
     * @access  public
     * @return  void
     */
    public function add()
    {
        $this->load->view('main_info');
    }


    /**
     * 修改站点
     *
     * @access  public
     * @return  void
     */
    public function edit($id)
    {
        $id = intval($id);
        $this->db->from('site')->where('s_id', $id);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data['id']  = $id;
            $data['res'] = $query->row_array();
        }
        $this->load->view('main_info', $data);
    }

    /**
     * 提交处理
     *
     * @access  public
     * @return  void
     */
    public function ok($act)
    {
        $this->load->library('dc_shell');
        $this->load->helper('dc_string');
        if ($act == 'add' || $act == 'edit') {
            $sql_data['is_visit']   = intval($this->input->post('is_visit'));
            $sql_data['uname']      = mv_bank($this->input->post('uname', TRUE));
            $sql_data['domain']     = str_replace(array(
                'http://',
                'https://',
                'www.',
                "\\"
            ), array(
                '',
                '',
                '',
                ''
            ), mv_bank($this->input->post('domain')));
            $sql_data['dir']        = mv_bank($this->input->post('dir'));
            $sql_data['is_ftp']     = intval($this->input->post('is_ftp'));
            $sql_data['ftp_user']   = mv_bank($this->input->post('ftp_user'));
            $sql_data['ftp_pwd']    = mv_bank($this->input->post('ftp_pwd'));
            $sql_data['is_mysql']   = intval($this->input->post('is_mysql'));
            $sql_data['mysql_user'] = strlen(mv_bank($this->input->post('mysql_user'))) > 16 ? substr(mv_bank($this->input->post('mysql_user')), 0, 16) : mv_bank($this->input->post('mysql_user')); //不能超过16位
            $sql_data['mysql_pwd']  = mv_bank($this->input->post('mysql_pwd'));
            $sql_data['mysql_base'] = mv_bank($this->input->post('mysql_base'));
            $sql_data['addtime']    = time();


            /* 得到执行脚本通用参数 */
            //用后面的端口:符合来区分是正式域名还是临时域名
            $domains = explode(':', $sql_data['domain']);
            //判断是正式域名还是临时域名
            $type    = count($domains) < 2 ? '1' : '2';
            //得到域名
            $domain  = reset($domains);
            //得到端口
            $ports   = count($domains) < 2 ? '80' : end($domains);

            $sql_data['domain'] = $domain;
            $sql_data['ports']  = $ports;
        }

        /* 增加站点 */
        if ($act == 'add') {

            $data['act'] = 'add';

            /* 判断必填项 */
            if (empty($sql_data['uname']) || empty($sql_data['domain']) || empty($sql_data['dir'])) {
                $data['message'] = '必填项为空!';
                $this->load->view('main_ok', $data);
                return;
            }

            /* 判断该站点是否存在，域名+目录是否存在  */
            $this->db->select('s_id')->from('site')->where("(domain = '" . $sql_data['domain'] . "' AND ports = '" . $ports . "') OR dir = '" . $sql_data['dir'] . "'");
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                $data['message'] = '该站点域名及目录已经存在，请核实!';
                $this->load->view('main_ok', $data);
                return;
            }

            /* 插入到数据库 */
            $this->db->insert('site', $sql_data);

            /* 执行脚本:增加站点，还会建立目录文件夹 */

            $shell_res['siteadd'] = $this->dc_shell->allin('siteadd', array(
                'dir' => $sql_data['dir'],
                'type' => $type,
                'domain' => $domain,
                'port' => $ports
            ));

            /* 执行脚本：如果站点暂时不开通就将刚刚添加好的域名删除绑定 */
            if (empty($sql_data['is_visit'])) {
                $shell_res['sitedel'] = $this->dc_shell->allin('sitedel', array(
                    'del_type' => '1',
                    'dir' => $sql_data['dir'],
                    'type' => $type,
                    'domain' => $domain,
                    'port' => $ports
                ));
            }

            /* 执行脚本:增加FTP */
            if (!empty($sql_data['is_ftp'])) {
                if (!empty($sql_data['ftp_user']) && !empty($sql_data['ftp_pwd']) && !empty($sql_data['dir'])) {
                    $shell_res['ftpadd'] = $this->dc_shell->allin('ftpadd', array(
                        'ftp_user' => $sql_data['ftp_user'],
                        'ftp_pwd' => $sql_data['ftp_pwd'],
                        'dir' => $sql_data['dir']
                    ));
                } else {
                    $shell_res['ftpadd'] = 'FTP设置为开通，必须填写FTP相关信息';
                }
            }
            $shell_res['httpd'] = $shell_res['sitedel'] == 'success' || $shell_res['siteadd'] == 'success' ? '1' : '0';
            /* 执行脚本:增加MYSQL */
            if (!empty($sql_data['is_mysql'])) {
                if (!empty($sql_data['mysql_base']) && !empty($sql_data['mysql_user']) && !empty($sql_data['mysql_pwd'])) {
                    $shell_res['mysqladd'] = $this->dc_shell->allin('mysqladd', array(
                        'mysql_base' => $sql_data['mysql_base'],
                        'mysql_user' => $sql_data['mysql_user'],
                        'mysql_pwd' => $sql_data['mysql_pwd']
                    ));
                } else {
                    $shell_res['mysqladd'] = 'MYSQL设置为开通，必须填写MYSQL相关信息';
                }
            }
            $data['shell_res'] = $shell_res;
            $this->load->view('main_ok', $data);
        }
        if ($act == 'edit') {

            $id                   = intval($_REQUEST['s_id']);
            $sql_data['edittime'] = time();
            $data['act']          = 'edit';

            /* 判断必填项 */
            if (empty($sql_data['uname']) || empty($sql_data['domain'])) {
                $data['message'] = '站点基本信息必填项为空!';
                $this->load->view('main_ok', $data);
                return;
            }


            /* 判断该站点是否存在
             *
             * 域名
             * FTP用户名
             *
             */
            $this->db->select('s_id')->from('site')->where("((domain = '" . $sql_data['domain'] . "' AND ports = '" . $ports . "') OR (ftp_user = '" . $sql_data['ftp_user'] . "' AND ftp_user<>''))  AND s_id <> " . $id);
            $query = $this->db->get();
            if ($query->num_rows() > 0) {
                $data['message'] = '和其他站点的域名或FTP用户名重复，请核实!';
                $this->load->view('main_ok', $data);
                return;
            }

            /* 去掉不能改的字段 */
            unset($sql_data['dir']);
            unset($sql_data['addtime']);

            /* 获取该站点所有信息，和新提交数据库对比方便执行脚本  */
            $this->db->from('site')->where('s_id', $id);
            $query = $this->db->get();
            $site  = $query->row_array();

            /* 执行脚本 */
            //站点访问或者域名提交了新的修改，就先删除原站点配置，然后添加新站点配置，注意仅删除域名绑定
            if ($sql_data['is_visit'] != $site['is_visit'] || ($sql_data['domain'] . $sql_data['ports'] != $site['domain'] . $site['ports'])) {

                //判断是正式域名还是临时域名
                $site_type = $site['ports'] == '80' ? '1' : '2';

                //删除原网站配置（仅域名绑定）
                $shell_res['sitedel'] = $this->dc_shell->allin('sitedel', array(
                    'del_type' => '1',
                    'dir' => $site['dir'],
                    'type' => $site_type,
                    'domain' => $site['domain'],
                    'port' => $site['ports']
                ));

                //如果站点设置可以访问就增加新的站点配置
                if (!empty($sql_data['is_visit'])) {
                    $shell_res['siteadd'] = $this->dc_shell->allin('siteadd', array(
                        'dir' => $site['dir'],
                        'type' => $type,
                        'domain' => $domain,
                        'port' => $ports,
                        'flag' => '1'
                    ));
                }
            }

            //修改FTP，三项中修改任意一项就删除老账户，增加新账户
            if ($sql_data['is_ftp'] != $site['is_ftp'] || $sql_data['ftp_user'] != $site['ftp_user'] || $sql_data['ftp_pwd'] != $site['ftp_pwd']) {
                //将原ftp账户删除
                $shell_res['ftpdel'] = $this->dc_shell->allin('ftpdel', array(
                    'ftp_user' => $site['ftp_user'],
                    's_user' => $this->s_user,
                    'dir' => $site['dir']
                ));

                //如果设置了开通FTP，就增加新的ftp账户
                if (!empty($sql_data['is_ftp'])) {
                    if (!empty($sql_data['ftp_user']) && !empty($sql_data['ftp_pwd'])) {
                        $shell_res['ftpadd'] = $this->dc_shell->allin('ftpadd', array(
                            'ftp_user' => $sql_data['ftp_user'],
                            'ftp_pwd' => $sql_data['ftp_pwd'],
                            'dir' => $site['dir']
                        ));
                    } else {
                        $sql_data['is_ftp']  = 0;
                        $shell_res['ftpadd'] = 'FTP设置为开通，必须填写FTP相关信息';
                    }
                }
            }

            //如果数据库为不开通状态
            if (empty($sql_data['is_mysql'])) {
                //如果之前没开通过数据库，什么也不做，如果之前开过就删除原来的数据库
                if (!empty($site['mysql_base'])) {

                    $shell_res['mysqldel'] = $this->dc_shell->allin('mysqldel', array(
                        'mysql_base' => $site['mysql_base'],
                        'mysql_user' => $site['mysql_user']
                    ));
                }

                //将表中信息清空
                $sql_data['mysql_base'] = '';
                $sql_data['mysql_user'] = '';
                $sql_data['mysql_pwd']  = '';

            } else {
                //如果数据库设置为开通状态

                //如果之前有开通过数据库
                if (!empty($site['mysql_base'])) {
					//就只能修改密码，将数据库名和用户名不写入数据库
					unset($sql_data['mysql_user']);
					unset($sql_data['mysql_base']);

                    //只需判断密码是否为空即可，并且数据库密码变化过，然后修改用户密码
                    if (!empty($sql_data['mysql_pwd']) && $sql_data['mysql_pwd'] != $site['mysql_pwd']) {
                        $shell_res['mysqledit'] = $this->dc_shell->allin('mysqledit', array(
                            'mysql_user' => $site['mysql_user'],
                            'mysql_pwd' => $sql_data['mysql_pwd']
                        ));

                        //表中的数据库名称和用户名称不能改变
                        unset($sql_data['mysql_base']);
                        unset($sql_data['mysql_user']);

                    } else {
                        if (empty($sql_data['mysql_pwd'])) {
                            $shell_res['mysqledit'] = '设置开MYSQL数据库，密码不能为空';
                        }
                        //不修改数据库信息
                        unset($sql_data['is_mysql']);
                        unset($sql_data['mysql_base']);
                        unset($sql_data['mysql_user']);
                        unset($sql_data['mysql_pwd']);
                    }
                } else {
                    /* 如果之前没有开通过数据库就增加全新数据库 */

                    //判断mysql基本信息是否填写好
                    if (!empty($sql_data['mysql_base']) && !empty($sql_data['mysql_user']) && !empty($sql_data['mysql_pwd'])) {
                        //先查询将要开通的数据库和用户是否已经存在
                        $this->db->select('s_id')->from('site')->where("mysql_base = '" . $sql_data['mysql_base'] . "' OR mysql_user='" . $sql_data['mysql_user'] . "'");
                        $query = $this->db->get();
                        if ($query->num_rows() > 0) {
                            //不修改数据库信息
                            unset($sql_data['is_mysql']);
                            unset($sql_data['mysql_base']);
                            unset($sql_data['mysql_user']);
                            unset($sql_data['mysql_pwd']);

                            $shell_res['mysqladd'] = '设置的数据库名称或者用户名是否被其他站点占用，请重新设置';
                        } else {
                            $shell_res['mysqladd'] = $this->dc_shell->allin('mysqladd', array(
                                'mysql_base' => $sql_data['mysql_base'],
                                'mysql_user' => $sql_data['mysql_user'],
                                'mysql_pwd' => $sql_data['mysql_pwd']
                            ));
                        }
                    } else {
                        //不修改数据库信息
                        unset($sql_data['is_mysql']);
                        unset($sql_data['mysql_base']);
                        unset($sql_data['mysql_user']);
                        unset($sql_data['mysql_pwd']);

                        $shell_res['mysqledit'] = '设置开MYSQL数据库，需要填写好MYSQL的基本信息';
                    }
                }

            }

            $shell_res['httpd'] = $shell_res['sitedel'] == 'success' || $shell_res['siteadd'] == 'success' ? '1' : '0';

            /* 更新站点数据库 */
            $this->db->where('s_id', $id);
            $this->db->update('site', $sql_data);
            $data['id']        = $id;
            $data['shell_res'] = $shell_res;
            $this->load->view('main_ok', $data);
        }


        if ($act == 'del') {
            $id                   = intval($_REQUEST['id']);
            $sql_data['status']   = 0;
            $sql_data['edittime'] = time();

            if (empty($id)) {
                $data['message'] = '请选择一个站点再操作！';
                $this->load->view('main_ok', $data);
                return;
            }

            /* 获取该站点所有信息，和新提交数据库对比方便执行脚本  */
            $this->db->from('site')->where('s_id', $id);
            $query = $this->db->get();
            if ($query->num_rows() < 1) {
                $data['message'] = '该站点不存在，请重新选择一个站点！';
                $this->load->view('main_ok', $data);
                return;
            } else {
                $site = $query->row_array();
            }

            //判断是正式域名还是临时域名
            $site_type = $site['ports'] == '80' ? '1' : '2';

            /* 彻底删除站点目录和域名绑定 */
            $shell_res['sitedel'] = $this->dc_shell->allin('sitedel', array(
                'del_type' => '2',
                'dir' => $site['dir'],
                'type' => $site_type,
                'domain' => $site['domain'],
                'port' => $site['ports']
            ));

            /* 删除FTP */
            if (!empty($site['ftp_user'])) {
                $shell_res['ftpdel']  = $this->dc_shell->allin('ftpdel', array(
                    'ftp_user' => $site['ftp_user'],
                    's_user' => $this->s_user,
                    'dir' => $site['dir']
                ));
                $sql_data['is_ftp']   = '0';
                $sql_data['ftp_user'] = '';
                $sql_data['ftp_pwd']  = '';
            }

            /* 删除数据库 */
            if (!empty($site['mysql_base'])) {
                $shell_res['mysqldel']  = $this->dc_shell->allin('mysqldel', array(
                    'mysql_base' => $site['mysql_base'],
                    'mysql_user' => $site['mysql_user']
                ));
                $sql_data['is_mysql']   = '0';
                $sql_data['mysql_base'] = '';
                $sql_data['mysql_user'] = '';
                $sql_data['mysql_pwd']  = '';
            }

            $this->db->where('s_id', $id);
            $this->db->update('site', $sql_data);

            $data['shell_res'] = $shell_res;
            $data['act']       = 'del';
            $this->load->view('main_ok', $data);
        }

    }


    /*=============== AJAX ===============*/

    /**
     * 生成md16位，用Ajax来访问，post提交要加密的字符串
     *
     * @access  public
     * @return  string
     */
    public function ajax_md5()
    {
        $this->load->helper('dc_string');
        $md5_type = mv_bank($this->input->post('md5_type'));
        $md5_16   = mv_bank($this->input->post('md5_16'));
        if (!empty($md5_type) && !empty($md5_16)) {
            $mdb5_secret     = $md5_type == 'ftp' ? $this->ftp_secret : $this->mysql_secret;
            $data['message'] = substr(md5($md5_16 . $mdb5_secret), 8, 16);
        }
        $this->load->view('main_ajax', $data);
    }

    /**
     * 生成临时域名，用Ajax来访问，算法：先获取目前最大的端口号（如果找到的话就+1，没找到就从最新的临时域名端口开始）
     *
     * @access  public
     * @return  string
     */
    public function ajax_domain()
    {
        $this->db->select_max('ports')->from('site');
        $query = $this->db->get();
        $res   = reset($query->row_array());
        if ($res >= $this->domain_ports) {
            $ports           = $res + 1;
            $data['message'] = $this->domain_tmp . ':' . $ports;
        } else {
            $data['message'] = $this->domain_tmp . ':' . $this->domain_ports;
        }
        $this->load->view('main_ajax', $data);
    }

    /**
     * 判断站点之前是否存在数据库，如果存在就弹出删除确认
     *
     * @access  public
     * @return  string
     */
    public function ajax_mysql()
    {
        $id = $this->input->post('id');
        $this->db->select('s_id')->from('site')->where(array(
            's_id' => $id,
            'mysql_base <>' => ''
        ));
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data['message'] = '1';
        } else {
            $data['message'] = '0';
        }
        $this->load->view('main_ajax', $data);
    }

    /**
     * 重启apache
     *
     * @return  void
     */
    public function ajax_apache_reload()
    {
        $this->load->library('dc_shell');
        $res             = $this->dc_shell->allin('apache_reload');
        $data['message'] = $res;
        $this->load->view('main_ajax', $data);
    }

}